package com.alibaba.demo.controller;

import com.alibaba.demo.dao.UserDao;
import com.alibaba.demo.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Controller
public class UserController {

    @Autowired
    DataSource dataSource;

    @Autowired
    UserDao userDao;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    @ResponseBody
    public User main() {
        List<User> users =  userDao.findAllUsers();
        return users.get(1);
    }

    /**
     * @return 重定向到/main这个url在调用mainController里的方法跳转！
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login() throws SQLException {
        Connection connection = dataSource.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement("select * from t_user ");
        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()) {
            String username = resultSet.getString("loginName");
            System.out.println(username);
        }
        return "redirect:/main";
    }
}
